package handlers

import (
	"MBTIx/dba"
	"MBTIx/models"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
)

func Post_student(c *gin.Context) {
	db, _ := c.Get("db") //读取数据库连接池
	var student models.Student

	c.ShouldBind(&student)
	dba.InsertStudent(db.(*sqlx.DB), student) //插入数据
	dba.InsertPassword(db.(*sqlx.DB), student.Stu_id)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
	})
}

func Get_allStudent(c *gin.Context) {
	db, _ := c.Get("db")

	var students []models.Student
	dba.GetAllStudent(db.(*sqlx.DB), &students)

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": gin.H{
			"students": students,
		},
	})
}

func Update_student(c *gin.Context) {
	db, _ := c.Get("db")

	var student models.Student
	c.ShouldBind(&student)
	dba.UpdateStudent(db.(*sqlx.DB), student)

	c.JSON(http.StatusOK,gin.H{
		"code":0,
	})
}

func Delete_student(c *gin.Context) {
	db, _ := c.Get("db")

	var student models.Student
	c.ShouldBind(&student)
	dba.DeleteStudent(db.(*sqlx.DB), student.Stu_id)
	dba.DeleteTest(db.(*sqlx.DB), student.Stu_id)
	dba.DeletePassword(db.(*sqlx.DB), student.Stu_id)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
	})
}

func Get_student(c *gin.Context) {
	db, _ := c.Get("db")

	var student models.Student
	id := c.Params.ByName("id")
	dba.GetStudent(db.(*sqlx.DB), id, &student)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": gin.H{
			"students": student,
		},
	})
}

func Get_classStu(c *gin.Context) {
	db, _ := c.Get("db")

	var students []models.Student

	id := c.Params.ByName("id")
	dba.GetClassStudent(db.(*sqlx.DB), id, &students)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": gin.H{
			"students": students,
		},
	})
}

func Get_percenttage(c *gin.Context) {
	db, _ := c.Get("db")

	id := c.Params.ByName("id")
	var students []models.Student
	var student models.Student
	c.ShouldBind(&student)
	dba.GetClassStudent(db.(*sqlx.DB), id, &students)
	var sum, cnt int
	sum = len(students)
	for i := 0; i < sum; i++ {
		if students[i].Result == student.Result {
			cnt++
		}
	}
	ans := cnt * 100 / sum
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": gin.H{
			"per": ans,
		},
	})
}
